package com.sign2024.sign2024project.projecttask.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sign2024.sign2024core.common.constants.CommonConstants;
import com.sign2024.sign2024core.common.exeception.CommonException;
import com.sign2024.sign2024core.common.utils.StringUtils;
import com.sign2024.sign2024core.common.utils.TimeFormatUtils;
import com.sign2024.sign2024core.entry.projecttask.FormulaDefault;
import com.sign2024.sign2024core.entry.projecttask.ProjectTask;
import com.sign2024.sign2024project.projecttask.mapper.FormulaDefaultMapper;
import com.sign2024.sign2024project.projecttask.mapper.ProjectTaskMapper;
import com.sign2024.sign2024project.projecttask.mapper.RollbackRecordMapper;
import com.sign2024.sign2024project.projecttask.param.ProjectTaskParam;
import com.sign2024.sign2024project.projecttask.service.ProjectTaskService;
import com.sign2024.sign2024project.projecttask.vo.ProjectTaskListVo;
import com.sign2024.sign2024project.projecttask.vo.ProjectTaskVo;
import com.sign2024.sign2024project.projecttask.vo.RollbackVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 工程任务 数据层
 *
 * @author yujie
 * @data 2024/7/31 15:15
 */
@Service
public class ProjectTaskServiceImpl implements ProjectTaskService {

    @Resource
    private ProjectTaskMapper projectTaskMapper;

    @Resource
    private FormulaDefaultMapper formulaDefaultMapper;

    @Resource
    private RollbackRecordMapper rollbackRecordMapper;

    @Override
    public ProjectTask selectProjectTaskData(Integer id) {
        if (StringUtils.isNull(id)) {
            throw new CommonException(CommonConstants.ERROR, "任务id为空");
        }

        ProjectTask projectTask = projectTaskMapper.selectProjectTaskData(id);
        return projectTask;
    }

    @Override
    public ProjectTaskVo createTask(Integer taskState) {
        if (StringUtils.isNull(taskState)) {
            throw new CommonException(CommonConstants.ERROR, "任务标识为空");
        }

        // 指定日期格式为"yyMMdd"
        SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
        Date date = new Date();
        String nowDate = sdf.format(date);

        String yearMonthDay = formatDateToYearMonthDay(new Date());
        // 获取当天任务最大编号
        String code = projectTaskMapper.maxTaskCode(yearMonthDay, taskState);

        String taskCode = null;
        if (StringUtils.isNull(code)) {
            // 如果 code 为 null 当天没有编号， 开始编号
            taskCode = concatTaskCode(taskState, nowDate, "001");
        } else {
            // 不是空，字符串切割处理
            // 获取字符串后三位
            String str = code.substring(code.length() - 3);
            String incrementString = incrementString(str);
            // 任务编号
            taskCode = concatTaskCode(taskState, nowDate, incrementString);

        }

        // 获取 默认公式
        FormulaDefault defaultOne = formulaDefaultMapper.selectDefaultOne();

//        // 目前所需参数 任务标识 任务状态,0工程服务,1基建,2物资类
        ProjectTask projectTask = new ProjectTask();
        projectTask.setTaskState(taskState);
        projectTask.setTaskCode(taskCode);

        BeanUtils.copyProperties(defaultOne, projectTask);
        projectTaskMapper.createProjectTask(projectTask);

//        ProjectTask task = projectTaskMapper.selectById(projectTask.getId());
        ProjectTaskVo task = projectTaskMapper.selectTaskVo(projectTask.getId());

        return task;
    }

    @Override
    public int updateTask(ProjectTask projectTask) {
        return projectTaskMapper.updateProjectTask(projectTask);
    }


    @Override
    public Page<ProjectTaskListVo> pageProjectTask(ProjectTaskParam param) {
        Integer offset = (param.getPageNum() - 1) * param.getPageSize();
        param.setOffset(offset);

        // 处理时间参数
        if (StringUtils.isNotNull(param.getCreateTime())) {
            String monthDay = TimeFormatUtils.formatStrToYearMonthDay(param.getCreateTime());
            param.setCreateTime(monthDay);
        }

        // 分页查询
//        Page<ProjectTask> page = new Page<>(param.getPageNum(), param.getPageSize());
//        List<ProjectTask> projectTasks = projectTaskMapper.selectInfoByPage(param);
        Page<ProjectTaskListVo> page = new Page<>(param.getPageNum(), param.getPageSize());
        List<ProjectTaskListVo> projectTasks = projectTaskMapper.selectInfoByPage(param);

        // 页码
        page.setCurrent(param.getPageNum());
        page.setSize(param.getPageSize());

        // 总记录数
        Long aLong = projectTaskMapper.pageCount(param);
        page.setTotal(aLong);
        page.setRecords(projectTasks);

        return page;
    }

    @Override
    public void delFlagTask(Integer id) {
        projectTaskMapper.delFlagTask(id);
    }

    @Override
    public void updateDefault(FormulaDefault formulaDefault) {
        formulaDefaultMapper.updateDefault(formulaDefault);
    }

    @Override
    public FormulaDefault selectDefaultOne() {
        FormulaDefault formulaDefault = formulaDefaultMapper.selectDefaultOne();
        return formulaDefault;
    }

    @Override
    public FormulaDefault returnDefault() {
        // 清空原有数据
        formulaDefaultMapper.cleanDefault();
        // 添加默认数据
        FormulaDefault formulaDefault = new FormulaDefault();
        formulaDefault.setSkillFamily("家数");
        formulaDefaultMapper.insert(formulaDefault);

        // 最后必须确保 数据库中有一条数据
        FormulaDefault aDefault = formulaDefaultMapper.selectById(formulaDefault.getId());
        return aDefault;
    }

    @Override
    public List<RollbackVo> selectRollbackByTaskState(Integer taskState) {
        List<RollbackVo> list = rollbackRecordMapper.selectRollbackByTaskState(taskState);
        
        if (!list.isEmpty()) {
            // 进行数据处理
            for (RollbackVo vo : list) {
                List<String> strList = new ArrayList<>();
                if (StringUtils.isNotNull(vo.getFileName())) {
                    strList.add(vo.getFileName());
                }

                if (StringUtils.isNotNull(vo.getFileNameTwo())) {
                    strList.add(vo.getFileNameTwo());
                }

                vo.setFileList(strList);
            }
        }

        return list;
    }


    /**
     * 格式化时间为“年月日”形式的方法
     *
     * @param date 时间
     * @return
     */
    public static String formatDateToYearMonthDay(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(date);
    }

    /**
     * 将 三位 数字型字符串 加一
     *
     * @param str 字符串 例如 001
     * @return
     */
    public static String incrementString(String str) {
        // 将字符串转换为整数
        int number = Integer.parseInt(str);
        // 对整数加一
        number++;
        // 将整数转换回字符串，并补充前导零
        return String.format("%03d", number);
    }


    /**
     * 拼接 任务编号
     *
     * @param number  任务标识
     * @param timeStr 时间字符串
     * @param codeNum 编号
     * @return 任务编号
     */
    public static String concatTaskCode(Integer number, String timeStr, String codeNum) {
        String chosenString;

        // 根据整数选择一个字符串
        switch (number) {
            case 0:
                chosenString = "GC";
                break;
            case 1:
                chosenString = "JJ";
                break;
            case 2:
                chosenString = "WZ";
                break;
            default:
                throw new CommonException(CommonConstants.ERROR, "任务标识错误");
        }

        // 拼接选择出的字符串与其他两个字符串
        return chosenString + timeStr + codeNum;
    }
}
